package cn.itsource.pethome.pay.service.impl;

import cn.itsource.pethome.basic.service.impl.BaseServiceImpl;
import cn.itsource.pethome.order.domain.OrderProduct;
import cn.itsource.pethome.order.service.IOrderProductService;
import cn.itsource.pethome.pay.config.AlipayConfig;
import cn.itsource.pethome.pay.domain.AlipayInfo;
import cn.itsource.pethome.pay.domain.PayBill;
import cn.itsource.pethome.pay.domain.PayConstants;
import cn.itsource.pethome.pay.mapper.PayBillMapper;
import cn.itsource.pethome.pay.service.IAlipayInfoService;
import cn.itsource.pethome.pay.service.IPayBillService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class PayBillServiceImpl extends BaseServiceImpl<PayBill> implements IPayBillService {

    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IOrderProductService orderProductService;

    /**
     *  需要根据传来的支付单号判断该调用哪个支付的方法
     * @param payBill 支付单
     * @return
     */
    @Override
    public String goPay(PayBill payBill) {
        switch (payBill.getPayChannel()){
            case 0:     //余额支付
                break;
            case 1:     //支付宝支付
                //先根据payBill中的shop_id 查询到商家的信息，公钥、私钥和APPID
                AlipayInfo alipayInfo = alipayInfoService.loadByShopId(payBill.getShop_id());
                //将商家信息和支付订单信息传入，发起请求
                String resultPay = aliPay(alipayInfo,payBill);
                return resultPay;
            case 2:     //微信支付
                break;
            default:    //其他支付
                break;
        }
        return null;
    }

    @Override
    public PayBill loadByOrderSn(String out_trade_no) {
        return payBillMapper.loadByOrderSn(out_trade_no);
    }

    @Override
    @Transactional
    public void updateByOrderSn(String out_trade_no, String trade_no) {
        //1.根据商户订单号 查询对应的订单
        PayBill payBill = loadByOrderSn(out_trade_no);
        payBill.setState(1);
        payBill.setUpdateTime(new Date());
        payBill.setUnionPaySn(trade_no);
        payBillMapper.update(payBill);
        switch (payBill.getBusinessType()){
            case PayConstants.BUSINESSTYPE_PRODUCT:
                //根据业务类型 更新不同的订单
                OrderProduct orderProduct = orderProductService.loadById(payBill.getBusinessKey());
                orderProduct.setState(1);
                orderProduct.setPaySn(trade_no);
                orderProductService.update(orderProduct);
                break;
            case PayConstants.BUSINESSTYPE_GOODS:
                break;
        }

    }

    private String aliPay(AlipayInfo alipayInfo, PayBill payBill){
        AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipaydev.com/gateway.do" ,
                alipayInfo.getAppid(), alipayInfo.getMerchant_private_key(),
                "json", AlipayConfig.charset, alipayInfo.getAlipay_public_key(), AlipayConfig.sign_type);  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url); //在公共参数中设置回跳和通知地址
        /*
        *   out_trade_no	String	必选	64	商户订单号。64 个字符以内的大小，
        * 可包含字母、数字、下划线。需保证该参数在商户端不重复
            product_code	String	必选	64	销售产品码，与支付宝签约的产品码名称。
          注：目前电脑支付场景下仅支持FAST_INSTANT_TRADE_PAY
            total_amount	Price	必选	11	订单总金额，单位为元，精确到小数点后两位，
          取值范围为 [0.01,100000000]。金额不能为0。
            subject	String	必选	256	订单标题
        * */
        String out_trade_no = payBill.getOrderSn();
        String total_amount = payBill.getMoney().toString();
        String subject="宠物之家服务订单";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form= "" ;
        try  {
            form= alipayClient.pageExecute(alipayRequest).getBody();
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
       return form;
    }
}
